<template>
  <div class="login-container">
    <div class="login-box">
      <div class="login-title">物流系统登录</div>
      <el-tabs v-model="activeTab" class="login-tabs">
        <el-tab-pane label="账号登录" name="account">
          <el-form :model="loginForm" :rules="rules" ref="loginFormRef" class="login-form">
            <el-form-item prop="username">
              <el-input
                  v-model="loginForm.username"
                  placeholder="用户名/电话号码"
                  :prefix-icon="User"
                  size="large"
              />
            </el-form-item>
            <el-form-item prop="password">
              <el-input
                  v-model="loginForm.password"
                  type="password"
                  placeholder="请输入密码"
                  :prefix-icon="Lock"
                  size="large"
                  show-password
              />
            </el-form-item>
            <el-form-item>
              <el-checkbox v-model="loginForm.remember">记住我</el-checkbox>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" size="large" class="login-btn" @click="onLogin"
              >登录</el-button
              >
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="手机号登录" name="phone">
          <el-form :model="phoneForm" :rules="phoneRules" ref="phoneFormRef" class="login-form">
            <el-form-item prop="phone">
              <el-input
                  v-model="phoneForm.phone"
                  placeholder="请输入手机号"
                  :prefix-icon="Cellphone"
                  size="large"
                  maxlength="11"
              />
            </el-form-item>
            <el-form-item prop="code">
              <el-row :gutter="8" style="width: 100%">
                <el-col :span="16">
                  <el-input
                      v-model="phoneForm.code"
                      placeholder="请输入验证码"
                      :prefix-icon="Message"
                      size="large"
                      maxlength="6"
                  />
                </el-col>
                <el-col :span="8">
                  <el-button
                      :disabled="countdown > 0"
                      size="large"
                      @click="sendCode"
                      style="width: 100%"
                  >
                    <span v-if="countdown === 0" @click="sendCode">获取验证码</span>
                    <span v-else>{{ countdown }}s</span>
                  </el-button>
                </el-col>
              </el-row>
            </el-form-item>
            <el-form-item>
              <el-checkbox v-model="phoneForm.remember">记住我</el-checkbox>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" size="large" class="login-btn" @click="onPhoneLogin"
              >登录</el-button
              >
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>
      <div class="login-links">
        <a href="#" @click.prevent="onForgot">忘记密码？</a>
        <span>|</span>
        <a href="#" @click.prevent="onRegister">注册账号</a>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { User, Lock, Cellphone, Message } from '@element-plus/icons-vue'
import {login, phone, phonelogin} from "@/assets/user.js";
import {useUserStore} from "@/pinia/index.js";
// import routes from 'vue-router/auto/routes'
// import {routes} from "vue-router/auto-routes";

const route = useRoute()
const activeTab = ref('account')

// 账号登录表单
const loginForm = ref({
  username: '',
  password: '',
  remember: false,
})
const rules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
}
const loginFormRef = ref(null)

// 手机号登录表单
const phoneForm = ref({
  phone: '',
  code: '',
  remember: false,
})
const phoneRules = {
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' },
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { pattern: /^\d{6}$/, message: '验证码为6位数字', trigger: 'blur' },
  ],
}
const phoneFormRef = ref(null)

// 验证码倒计时
const countdown = ref(0)
let timer = null
const sendCode = async () => {
  if (!/^1[3-9]\d{9}$/.test(phoneForm.value.phone)) {
    ElMessage.error('请输入正确的手机号')
    return
  }
  
  try {
    const res = await phone(phoneForm.value.phone)
    if (res.data.code === 200) {
      ElMessage.success('验证码已发送！')
      countdown.value = 60
      timer = setInterval(() => {
        countdown.value--
        if (countdown.value <= 0) {
          clearInterval(timer)
          timer = null
        }
      }, 1000)
    } else {
      ElMessage.error(res.data.message || '验证码发送失败')
    }
  } catch (error) {
    ElMessage.error('验证码发送失败，请重试')
  }
}
const userStore = useUserStore();
const onLogin = () => {
  login(loginForm.value).then(res=>{
    console.log(res.data.data)
    if(res.data.code==200){
      if(res.data.data.rname=="普通用户"){
        window.location.href = '/user'
      }else if(res.data.data.rname=="配送员"){
        window.location.href = '/delivery'
      }else if(res.data.data.rname=="管理员") {
        window.location.href = '/admin'
      }
      ElMessage.success('登录成功！')
      userStore.setUser(res.data.data)
      userStore.setId(res.data.data.id)
      userStore.setUsername(res.data.data.username)
      console.log(res.data.data)

      localStorage.setItem("token",res.data.data.token);
    }else{
      ElMessage.error(res.data.message)
    }

  })
}
const onPhoneLogin = () => {
  phonelogin(phoneForm.value).then(res=>{
    console.log(res.data.data)
    if(res.data.code==200){
      if(res.data.data.rname=="普通用户"){
        window.location.href = '/user'
      }else if(res.data.data.rname=="配送员"){
        window.location.href = '/delivery'
      }else if(res.data.data.rname=="管理员") {
        window.location.href = '/admin'
      }
      ElMessage.success('登录成功！')
      localStorage.setItem("user",res.data.data);
      localStorage.setItem("token",res.data.data.token);
    }else{
      ElMessage.error(res.data.message)
    }
})
}
const onForgot = () => {
  // 跳转到找回密码页面
  window.location.href = '/forgot'
}
const onRegister = () => {
  // 跳转到注册页面
  window.location.href = '/register'
}

onMounted(() => {
  // 自动填充手机号和密码
  if (route.query.username && route.query.password) {
    activeTab.value = 'phone'
    phoneForm.value.phone = route.query.username
    phoneForm.value.code = ''
    phoneForm.value.remember = false
    // 自动填充密码到账号登录（如有需要可同步）
    loginForm.value.username = route.query.username
    loginForm.value.password = route.query.password
    phoneForm.value.password = route.query.password // 备用
    // 自动填充密码到手机号登录（如有需要）
    // 这里可根据实际业务调整
    loginForm.value.remember = false
  }
})
</script>

<style scoped>
.login-container {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: url('src/assets/images/8e758213fe1079acaad71e828c5888f1.jpg') center/cover no-repeat;
}
.login-box {
  background: #fff;
  padding: 48px 40px 32px 40px;
  border-radius: 16px;
  box-shadow: 0 8px 32px 0 rgba(31, 38, 135, 0.2);
  min-width: 360px;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.login-title {
  font-size: 2rem;
  font-weight: bold;
  color: #2980b9;
  margin-bottom: 32px;
  letter-spacing: 2px;
}
.login-tabs {
  width: 100%;
  margin-bottom: 0;
}
.login-form {
  width: 100%;
  margin-top: 24px;
}
.login-btn {
  width: 100%;
  font-size: 1.1rem;
  letter-spacing: 1px;
}
.login-links {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  margin-top: 8px;
  font-size: 0.95rem;
  color: #888;
}
.login-links a {
  color: #2980b9;
  text-decoration: none;
  margin: 0 4px;
  transition: color 0.2s;
}
.login-links a:hover {
  color: #6dd5fa;
}
</style>

